import { Component, OnInit } from '@angular/core';
import { BladeContainerBase } from "../../../../shared/blade/blade-container-base";
import { FormBuilder, Validators, FormControl } from "@angular/forms";
import { DatePipe } from "@angular/common";
import { Command } from "../../../../shared/toolbar.service";
import { Observable } from "rxjs/Observable";

import { Role } from "../../../../entity/role.model";
import { RoleService } from "../../../../service/role.service";

@Component({
  selector: 'app-role-edit',
  templateUrl: './role-edit.component.html',
  styleUrls: ['./role-edit.component.css']
})
export class RoleEditComponent extends BladeContainerBase<Role>{

  roles: Role[] = [];
  reuseId: number;

  constructor(
    private datePipe: DatePipe,
    private fb: FormBuilder,
    private roleService: RoleService,
  ) {
    super(fb);
  }

  ngOnInit(): void {
    //编辑时保存按钮和重置命令    
    if (!this.isNew) {
      this.commands = [
        new Command("save", "保存", "fa fa-save", "setofkey:update", (blade) => this.exeSaveChange(blade), (blade) => this.canSaveChange(blade)),
        new Command("reset", "重置", "fa fa-save", "setofkey:reset", (blade) => this.exeReset(blade), (blade) => this.canReset(blade)),
      ]
    }
    else {
      this.initData();
      this.currentEntity = new Role(0, "", "");
    }
    super.ngOnInit();

  }

  initData(): any | Observable<any> | Promise<any> {
    if (this.isNew) {
      this.roleService.getRoles()
        .then(res => {
          if (!res) { return false };
          this.roles = [...res];
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  exeSaveChange(blade: any): void {
    this.saveChange();
  }
  canSaveChange(blade: any): boolean {
    return this.hasChange() && !this.hasError();
  }
  exeReset(blade: any): void {
    return this.formGroup.reset(this.currentEntity);
  }
  canReset(blade: any): boolean {
    return this.hasChange();
  }


  /**
   * 创建表单
   * 
   * @memberof RoleEditComponent
   */
  createForm() {
    this.formGroup = this.fromBuider.group({
      "roleName": [this.currentEntity.roleName, [
        Validators.required,
        // Validators.pattern("[\u4e00-\u9fa5]{1,20}"),
        Validators.maxLength(20),
      ],],
      // (control: FormControl): any => this.roleNameAsnyValidator(control)  
      "roleDesc": [this.currentEntity.roleDesc, [
        // Validators.required,
        Validators.maxLength(20),
      ],],
      "reuseId": [this.currentEntity.reuseId, [],],

    });
  }

  /**
   * 设置错误对象
   * 
   * @memberof RoleEditComponent
   */
  setFormError(): void {
    this.formErrors = {
      'roleName': '',
      'roleDesc': '',
      'basicsRoleId': '',
    };
  }


  /**
   * 设置表单验证信息
   * 
   * @memberof RoleEditComponent
   */
  setValidationMessages(): void {
    this.validationMessages = {
      'roleName': {
        'required': '不能为空。',
        'pattern': '由汉字组成。',
        'maxlength': '不能多于20个字符长度。',
        'exist': '已存在。',
      },
      'roleDesc': {
        'required': '不能为空。',
        'pattern': '由汉子组成。',
        'maxlength': '不能多于20个字符长度。',
        'exist': '已存在。',
      },
      'basicsRoleId': {}
    };
  }



  /**
   * 异步校验角色名称是否存在
   * 
   * @param {FormControl} control 
   * @returns {*} 
   * @memberof RoleEditComponent
   */
  roleNameAsnyValidator(control: FormControl): any {
    if (!control.value || control.value == this.currentEntity.roleName) {
      return Observable.of(null);
    }
    return this.roleService.hasRoleName(control.value, this.currentEntity.roleId)
      .map(res => res ? { exist: true } : null);
  }



  /**
   * 新增
   * 
   * @memberof RoleEditComponent
   */
  onCreate() {
    if (!this.hasError()) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value;
      this.currentEntity.roleName = formValue.roleName;
      this.currentEntity.roleDesc = formValue.roleDesc;
      this.currentEntity.reuseId = this.reuseId;
      // let entity = {
      //   roleId: 0,        
      //   roleName:formValue.roleName,
      //   roleDesc:formValue.roleDesc,
      // }
      this.roleService.create(this.currentEntity)
        .then(res => {
          if (res == 200) {
            let parentContainerInstance = this.parentBlade.bladeContainerInstance;
            parentContainerInstance.refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }


  /**
   * 更新
   * 
   * @returns {(any | Promise<any> | Observable<any>)} 
   * @memberof RoleEditComponent
   */
  saveChange(): any | Promise<any> | Observable<any> {
    if (this.canSaveChange(this.currentBlade)) {
      this.bladeData.isLoading = true;
      let formValue = this.formGroup.value;
      this.currentEntity.roleName = formValue.roleName;
      this.currentEntity.roleDesc = formValue.roleDesc;
      this.currentEntity.reuseId = formValue.reuseId;
      return this.roleService.update(this.currentEntity)
        .then(res => {
          if (res) {
            (this.parentBlade.bladeContainerInstance).refresh(res);
            this.bladeService.closeBlade(this.currentBlade);
            return true;
          }
        })
        .catch(error => this.bladeData.error = error)
        .then(res => this.bladeData.isLoading = false);
    }
  }

  onRoleIsChecked(check: boolean, role: Role) {
    this.reuseId = role.roleId;
  }

}



// WEBPACK FOOTER //
// ./src/app/module/admin/role/role-edit/role-edit.component.ts